import 'dart:convert';

import 'package:cron/cron.dart';
import 'package:dio/dio.dart';
import 'package:mysql_client/mysql_client.dart';

const String useApplySyncUrl="/syncElevatorInfo";
const String reformAlterApplySyncUrl="/syncAlterApplyAlteration";
const String shiftAlterApplySyncUrl="/syncAlterApplyShift";
const String enterpNameAlterApplySyncUrl="/syncAlterApplyName";
const String enterpAlterApplySyncUrl="/syncAlterApplyUnit";
const String elevScrapSyncUrl="/syncCancelApply";
const String elevUseStopSyncUrl="/syncElevUseStop";


final cron = Cron();

final dio = Dio()..options = BaseOptions(
  // baseUrl: "http://localhost:8996",
  baseUrl: "http://113.201.64.105:86/jeecg-boot/ttsx/sync",
  responseType: ResponseType.json,
);


void startJob() {
  cron.schedule(Schedule.parse('0 0 12 * *'), () async {
    print("定时任务执行");

    var now = DateTime.now();
    var date =  DateTime(now.year, now.month, now.day-1);
    var dateStr = "${date.year}-${date.month}-${date.day} 12:00:00";
    getCdcSyncData(dateStr);

  });
}

void getCdcSyncData(String dateStr) async {

  try {
    final conn = await MySQLConnection.createConnection(
      host: "10.16.88.61",
      port: 3306,
      userName: "root",
      password: "!QAZ1qaz4rfv2",
      databaseName: "sesisp",
      secure: false,
    );

// actually connect to database
    await conn.connect();

    var result = await conn.execute("SELECT * FROM sync_cdc_record WHERE data_type NOT LIKE '%ELEV_SYNC%' AND creat_time >= :date", {"date": dateStr});

    if (result.rows.isEmpty) {
      print("未获取到数据");
    }

    for (final row in result.rows) {
       sendData(row.assoc());
    }

    conn.close();
  } catch (e) {
    print("连接Mysql失败 : $e");
  }
}

void sendData(Map item)  async {

  String data = item["data"];
  String id = item["id"];
  String dataType = item["data_type"];

  String syncUrl = "";
  String tip = "";

  if (dataType == "USE_APPLY") {
    syncUrl = useApplySyncUrl;
    tip = "[注册使用登记同步]";
  } else if (dataType == "ELEV_SCRAP") {
    syncUrl = elevScrapSyncUrl;
    tip = "[注销电梯同步]";
  } else if (dataType == "ELEV_USE_STOP") {
    syncUrl = elevUseStopSyncUrl;
    tip = "[电梯停用启用同步]";
  } else if (dataType == "REFORM_ALTER_APPLY") {
    syncUrl = reformAlterApplySyncUrl;
    tip = "[改造变更登记同步]";
  } else if (dataType == "SHIFT_ALTER_APPLY") {
    syncUrl = shiftAlterApplySyncUrl;
    tip = "[移装变更登记同步]";
  }else if (dataType == "ENTERP_ALTER_APPLY") {
    syncUrl = enterpAlterApplySyncUrl;
    tip = "[单位变更登记同步]";
  }else if (dataType == "ENTERP_NAME_ALTER_APPLY") {
    syncUrl = enterpNameAlterApplySyncUrl;
    tip = "[单位更名登记同步]";
  }

  if (syncUrl != "") {
    Map body = jsonDecode(data);
    final response = await dio.post(syncUrl, data: body);
    var result = response.data;
    print("$tip---$id---$result");
  }
}
